<?php

namespace App\Services;

use App\Models\MoneyLog;
use App\User;
use common\enum\MoneyLogEnum;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class MoneyLogService
{
    /**
     * 交易类别：充值
     *
     * @var int
     */
    const CATEGORY_DEPOSIT = 1;

    /**
     * 交易类别： 提款
     *
     * @var int
     */
    const CATEGORY_WITHDRAW = 2;

    /**
     * 交易类别： 注单
     *
     * @var int
     */
    const CATEGORY_ORDER = 3;

    /**
     * 交易类别： 额度转换
     *
     * @var int
     */
    const CATEGORY_TRANS = 4;

    /**
     * 交易类别： 优惠
     *
     * @var int
     */
    const CATEGORY_COUPON = 5;

    /**
     * 交易类别： 返水
     *
     * @var int
     */
    const CATEGORY_REBET = 6;

    /**
     * 交易类别：冲销
     *
     * @var int
     */
    const CATEGORY_REVOKE = 7;


    //获取交易记录分类
    public static function getRecordMenu()
    {
        $menu = self::getMoneyLogTypeFlat();
        return $menu['category'];
    }

    /**
     * 查询用户流水记录列表
     * @param int $pageIndex
     * @param int $pageSize
     * @param array $condtion
     */
    public static function getResult($userId, $attrs)
    {
        $page = isset($attrs['page']) ? $attrs['page'] : 1;
        $pageSize = isset($attrs['page_size']) ? $attrs['page_size'] : 20;
        // 参数格式化
        list($where, $between) = self::parseParams($userId, $attrs);
        $select = [
            "id",
            "order_number",
            "created_at",
            "category",//大类：交易类别：1充值，2提款，3注单，4额度转换，5优惠，6返水
            "type",//小类：交易类型 (1xx, 2xx, 3xx 与大类对应)
            "balance",//当前余额
            "amount",//交易金额
            "coupon_amount",//优惠，返水，退佣金额
            "remark"
        ];
        $sqlObj = MoneyLog::select($select)->where($where)->orderBy("id", "desc");
        if (!empty($between)) {
            $sqlObj->whereBetween('created_at', $between);
        }
        $deallog = get_page_data($sqlObj, $page, $pageSize);
        return $deallog;
    }

    /**
     * 获取用户总收入
     * @param int $userId
     * @param array $params
     */
    public static function getTotalIncomeMoney($userId, $params)
    {
        $params['category'] = 1;
        // 参数格式化
        list($where, $between) = self::parseParams($userId, $params);
        $sqlObj = MoneyLog::select(DB::raw('sum(amount + coupon_amount) AS amount'))->where($where);
        if (!empty($between)) {
            $sqlObj->whereBetween('created_at', $between);
        }
        $re = $sqlObj->first()->toArray();
        return current($re) ? current($re) : 0;
    }

    /**
     * 获取用户总支出
     * @param int $userId
     * @param array $params
     */
    public static function getTotalPayMoney($userId, $params)
    {
        $params['category'] = 2;
        // 参数格式化
        list($where, $between) = self::parseParams($userId, $params);
        $select = [
            DB::raw('sum(amount + coupon_amount) AS amount'), //交易金额
        ];
        $sqlObj = MoneyLog::select($select)->where($where);
        if (!empty($between)) {
            $sqlObj->whereBetween('created_at', $between);
        }
        $re = $sqlObj->first()->toArray();
        return current($re) ? current($re) : 0;
    }

    public static function formatMoneyLog($moneyLogs)
    {
        $dealtype = static::getMoneyLogTypeFlat();
        foreach ($moneyLogs as &$v) {
            $v['category'] = isset($dealtype['category'][$v['category']]) ? $dealtype['category'][$v['category']] : '';
            $v['type'] = isset($dealtype['type'][$v['type']]) ? $dealtype['type'][$v['type']] : '';
            $v['deal_money'] = $v['amount'] + $v['coupon_amount'];
        }
        return $moneyLogs;
    }

    public static function parseParams($userId, $attrs)
    {
        $between = [];
        $where[] = ['user_id', '=', $userId];
        if (isset($attrs['time_begin'])) {
            $between['time_begin'] = date('Y-m-d H:i:s', strtotime($attrs['time_begin']));
        } else {
            $between['time_begin'] = date('Y-m-d 00:00:00');
        }
        if (isset($attrs['time_end'])) {
            $between['time_end'] = date('Y-m-d H:i:s', strtotime($attrs['time_end']));
        } else {
            $between['time_end'] = date('Y-m-d 23:59:59');
        }
        if (isset($attrs['category'])) {
            $where[] = ['category', $attrs['category']];
        }
        return [$where, $between];
    }


    public static function getMoneyLogTypeFlat()
    {
        $type = [];
        foreach (self::getMoneyLogTypes() as $types) {
            $type = array_merge($type, $types['children']);
        }
        $result['category'] = array_column(self::getMoneyLogTypes(), 'name', 'id');
        $result['type'] = array_column($type, 'name', 'id');
        return $result;
    }

    public static function getMoneyLogTypes()
    {
        return [
            [
                'id' => self::CATEGORY_DEPOSIT,
                'name' => __('message.deposit'),
                'children' => [
                    ['id' => MoneyLogEnum::USER_DEPOSIT_ONLINE, 'name' => '线上入款'],
                    ['id' => MoneyLogEnum::USER_DEPOSIT_COMPANY, 'name' => '公司入款'],
                    ['id' => MoneyLogEnum::USER_DEPOSIT_MANUAL_ADD, 'name' => '手动增加余额'],
                ]
            ],
            [
                'id' => self::CATEGORY_WITHDRAW,
                'name' => __('message.withdraw'),
                'children' => [
                    ['id' => MoneyLogEnum::USER_WITHDROW_WITHDRAW, 'name' => '会员提款'],
                    ['id' => MoneyLogEnum::USER_WITHDROW_WITHDRAW_MANUAL, 'name' => '手动提款'],
                    ['id' => MoneyLogEnum::USER_WITHDROW_ONFREEZE, 'name' => '申请出款'],
                    ['id' => MoneyLogEnum::USER_WITHDROW_PRIZE_REDUCE, 'name' => '拒绝出款'],
                    ['id' => MoneyLogEnum::USER_WITHDROW_REDUCE_MANUAL, 'name' => '手动减少余额'],
                ]
            ],
            [
                'id' => self::CATEGORY_ORDER,
                'name' =>  __('message.order'),
                'children' => [
                    ['id' => MoneyLogEnum::USER_WITHDROW_BETTING, 'name' => '游戏下注'],
                    ['id' => MoneyLogEnum::USER_DEPOSIT_PRIZE_ADD, 'name' => '派奖'],
                    ['id' => MoneyLogEnum::USER_ORDER_ONFREEZE, 'name' => '追号冻结'],
                    ['id' => MoneyLogEnum::USER_ORDER_RESETTLE, 'name' => '重置派奖'],
                ]
            ],
            [
                'id' => self::CATEGORY_TRANS,
                'name' => __('message.transfer'),
                'children' => [
                    ['id' => MoneyLogEnum::USER_TRANSFER_MTOP, 'name' => '主转子钱包'],
                    ['id' => MoneyLogEnum::USER_TRANSFER_PTOM, 'name' => '子转主钱包'],
                    ['id' => MoneyLogEnum::USER_TRANSFER_MTOP_MANUAL, 'name' => '手动主转子钱包'],
                    ['id' => MoneyLogEnum::USER_TRANSFER_PTOM_MANUAL, 'name' => '手动子转主钱包'],
                ]
            ],
            [
                'id' => self::CATEGORY_COUPON,
                'name' => __('message.coupon'),
                'children' => [
                    ['id' => MoneyLogEnum::USER_DEPOSIT_REBET, 'name' => '返水优惠'],
                    ['id' => MoneyLogEnum::USER_DEPOSIT_MANUAL_REBET, 'name' => '手动发放返水'],
                    ['id' => MoneyLogEnum::USER_DEPOSIT_MANUAL_ACTIVITY, 'name' => '手动发放优惠'],
                    ['id' => MoneyLogEnum::USER_DEPOSIT_ACTIVITY, 'name' => '优惠活动'],
                    ['id' => MoneyLogEnum::USER_DEPOSIT_BETTING_REBET, 'name' => '下注返点'],
                    ['id' => MoneyLogEnum::USER_WITHDROW_DEDUCT_ACTIVITY, 'name' => '扣除优惠'],
                ]
            ],
            [
                'id' => self::CATEGORY_REBET,
                'name' => __('message.rebet'),
                'children' => [
                    ['id' => MoneyLogEnum::USER_DEPOSIT_REBET, 'name' => '返水优惠'],
                    ['id' => MoneyLogEnum::USER_DEPOSIT_MANUAL_REBET, 'name' => '手动发放返水'],
                ]
            ],
            [
                'id' => self::CATEGORY_REVOKE,
                'name' =>  __('message.revoke'),
                'children' => [
                    ['id' => MoneyLogEnum::USER_WITHDROW_REVOKE_REBET, 'name' => '返水冲销'],
                ]
            ]
        ];
    }


}
